<?php
/**
 * author      :chenwenwen
 * createTime  :2020-04-06 16:52
 * description :
 */

namespace app\admin\business;

use app\common\model\mysql\AdminUser as AdminUserModel;
use think\Exception;

class AdminUser {
    public static function login($data) {
        try {
            $adminUserObj = new AdminUserModel();
            $adminUser = self::getAdminUserByUsername($data['username']);
            if(empty($adminUser)) throw new Exception('用户名不存在');

            if ($adminUser['password'] != trim($data['password'])) throw Exception('密码错误');

            //记录登录信息
            $updateData = [
                'last_login_ip' => request()->ip(),
                'last_login_time' => time(),
                'update_time' => time()
            ];

            $res = $adminUserObj->updateById($adminUser['id'], $updateData);
            if (empty($res)) throw Exception('登录失败');
        } catch (\Exception $e) {
            //todo 记录错误日志 $e->getMessage()
            throw Exception($e->getMessage());
        }
        //记录session
        session(config('admin.session_admin'), $adminUser);

        return true;
    }


    /**
     * 通过用户名获取用户名称
     * @param $username
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminUserByUsername($username) {
        $adminUserObj = new AdminUserModel();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);
        if (false === $adminUser || empty($adminUser)) return false;
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}